package top.pengdong.pictureShare.mail.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import top.pengdong.pictureShare.common.model.R;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @description:
 * @projectName: RealHole
 * @see: com.pengshi.realhole.service
 * @author: pc
 * @createTime: 2022/2/14 19:26
 * @version: 1.0
 */
@Service
public class MailService {

	@Value("${spring.mail.username}")
	private String username;
	@Resource
	private JavaMailSender javaMailSender;
	@Resource
	private TemplateEngine templateEngine;

	/**
	 * @desc 发送验证邮件
	 * @param activationUrl 激活Url
	 * @param email 收件人邮箱
	 * @return
	 * @author pengshi
	 * @date 2022/2/14 19:28
	 **/
	@Async
	public R sendMailForActivationAccount(String activationUrl, String email) {
		// 创建邮件对象
		MimeMessage mimeMessage = javaMailSender.createMimeMessage();
		try {
			MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
			// 设置邮件主题
			message.setSubject("欢迎加入PictureShare树洞 —— 个人账号激活");
			// 设置邮箱发送者
			message.setFrom(username);
			// 设置邮件接收者，可以多个
			message.setTo(email);
			// 设置邮件抄送人，可以多个
			// message.setCc();
			// 设置隐秘抄送人，可以多个
			// message.setBcc();
			//设置邮件发送日期
			message.setSentDate(new Date());
			// 创建上下文环境
			Context context = new Context();
			context.setVariable("activationUrl", activationUrl);
			String text = templateEngine.process("activation-2.html", context);
			// 邮件发送
			message.setText(text, true);
		} catch (MessagingException e) {
			e.printStackTrace();
			return R.error("发送失败");
		}
		javaMailSender.send(mimeMessage);
		return R.ok("发送成功");
	}
}
